<template>
  <div class="view-fill">
    <div
      class="app-container-flex"
      v-if="!showModify.visible && !licenseDetail.visible"
    >
      <NewFullScreen
        v-model="showDialog"
        @returnBack="returnBack"
        :btn-list="btnList"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        :title="title"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="$permission('product:printDetail')"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <BasicInformation :info="infoList">
              <template v-slot:basic-licenseNumber>
                <p
                  v-if="$permission('productLicense:details')"
                  class="slip-edit"
                  @click="showLicenseDetail()"
                >
                  {{ infoList.data.licenseNumber || '-' }}
                </p>
                <p v-else>{{ infoList.data.licenseNumber || '-' }}</p>
              </template>
              <template v-slot:basic-brandName>
                <p class="slip-edit" @click="showBrandDetail()">
                  {{ infoList.data.brandName || '-' }}
                </p>
              </template>
              <template v-slot:basic-filePathList>
                <span v-if="infoList.data.filePathList">
                  <ele-gallery
                    :lazy="true"
                    :size="150"
                    :source="infoList.data.filePathList"
                    title="证照"
                  ></ele-gallery>
                </span>
                <span v-else>-</span>
              </template>
            </BasicInformation>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>证照信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="licenseInfoList">
              <template v-slot:basic-licenseNumber>
                <!-- 有证号才能进入 -->
                <p
                  v-if="
                    $permission('productLicense:details') &&
                    infoList.data.licenseNumber
                  "
                  class="slip-edit"
                  @click="showLicenseDetail()"
                >
                  {{ infoList.data.licenseNumber || '-' }}
                </p>
                <p v-else>{{ infoList.data.licenseNumber || '-' }}</p>
              </template>
              <template v-slot:basic-brandName>
                <p class="slip-edit" @click="showBrandDetail()">
                  {{ infoList.data.brandName || '-' }}
                </p>
              </template>
            </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>控制信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="controlInfoList"> </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>挂网信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="spreadInfoList">
              <template v-slot:basic-networkUnitCoefficient>
                <span>
                  {{ spreadInfoList.data.systemUnitCoefficient || '-' }}
                  {{ spreadInfoList.data.unitName }}
                </span>
                =
                <span>
                  {{ spreadInfoList.data.networkUnitCoefficient || '-' }}
                  {{ spreadInfoList.data.networkUnit }}
                </span>
              </template>
            </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>分类信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="classifyInfoList"> </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>医保信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="medicareInfoList"> </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>中标信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="bidderInfoList"> </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <!--<div class="model-panel-title">
            <p>供应商</p>
          </div>-->
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane
                  class="model-panel-title"
                  label="供应商"
                  name="supplier"
                >
                  <el-form
                    :model="tableInfo"
                    ref="tableForm"
                    style="width: 100%"
                  >
                    <PageTable
                      v-model:data="tableInfo.data"
                      :pager="false"
                      :check-box="false"
                      :tabIndex="true"
                      :field-list="tableInfo.fieldList"
                      :handle="tableInfo.handle"
                    >
                      <template v-slot:col-supplierName="scope">
                        <p class="slip-edit" @click="showSupplier(scope.row)">
                          {{ scope.row.supplierName || '-' }}
                        </p>
                      </template>
                      <template v-slot:col-orderNo="scope">
                        <p
                          v-if="
                            scope.row.contractList &&
                            scope.row.contractList.length
                          "
                        >
                          <span
                            class="slip-edit"
                            style="display: block"
                            v-for="item in scope.row.contractList"
                            @click="showOrder(item)"
                            :key="item.orderNo"
                          >
                            {{ item.orderNo }}
                          </span>
                        </p>
                        <span v-else>-</span>
                      </template>
                    </PageTable>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane
                  class="model-panel-title"
                  label="调价记录"
                  name="modifyPrice"
                  v-if="$permission('product:adjustPriceRecord')"
                >
                  <el-form
                    :model="adjustPriceTableInfo"
                    ref="tableForm"
                    style="width: 100%"
                  >
                    <PageTable
                      v-model:data="adjustPriceTableInfo.data"
                      :pager="false"
                      :check-box="false"
                      :tabIndex="true"
                      :field-list="adjustPriceTableInfo.fieldList"
                    />
                  </el-form>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <product-modify
      v-if="showModify.visible"
      v-model:visible="showModify.visible"
      :title="showModify.title"
      :type="showModify.type"
      :isCopy="showModify.isCopy"
      :detailId="id"
      @returnModify="modifyCallback"
    ></product-modify>
    <license-details
      v-if="licenseDetail.visible"
      :id="licenseDetail.id"
      v-model:visible="licenseDetail.visible"
      @returnBack="modifyCallback"
    ></license-details>
  </div>
</template>

<script setup name="productDetails">
import {
  getSupplierProductAll,
  setSupplierProductDefault,
  getProductById,
  getCoreProductRule,
} from '@/api/core'
import { adjustPriceSelectByProductId } from '@/api/purch'
import ProductModify from '@/views/product/product/modify'
import LicenseDetails from '@/views/product/license/details'
import EleGallery from '@/components/UploadImg/eleGallery'
import { orderOpAffairAll } from '@/api/affair'
import { doPrint } from '@/utils/exportUtil.js'
import { updatePrintCount } from '@/api/mapping'
import { selectByCodeAndDept } from '@/api/report.js'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: [String, Number],
  },
})
const title = ref('产品详情')
const activeName = ref('supplier')
const infoList = ref({
  data: {
    isConsignment: 0,
    withOperateTable: 0,
  },
  fieldList: [
    { label: '通用名称', value: 'commonName', type: 'text' },
    { label: '编码', value: 'code', type: 'text' },
    { label: 'his编码', value: 'hisCode', type: 'text' },
    { label: '别名', value: 'alias', type: 'text' },
    { label: '助记符', value: 'mnemonic', type: 'text' },
    { label: '产品类型', value: 'productTypeValue', type: 'text' },
    { label: '数量操作模式', value: 'qtyOperateModeValue', type: 'text' },
    { label: '规格', value: 'standard', type: 'text' },
    { label: '型号', value: 'modelNumber', type: 'text' },
    { label: '包装规格', value: 'packingSpecification', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '条码类型', value: 'codeTypeValue', type: 'text' },
    { label: '原厂主码', value: 'mainCode', type: 'text' },
    { label: '原厂码规则', value: 'g1Type', type: 'text' },
    { label: '计量单位', value: 'unitName', type: 'text' },
    { label: '上架状态', value: 'putShelfStatusValue' },
    {
      label: '产品长度(cm)',
      value: 'productLength',
      type: 'text',
    },
    {
      label: '产品宽度(cm)',
      value: 'productWidth',
      type: 'text',
    },
    {
      label: '产品高度(cm)',
      value: 'productHeight',
      type: 'text',
    },

    { label: '创建人', value: 'createUserName' },
    { label: '创建时间', value: 'createTime' },
    { label: '最近更新人', value: 'updateUserName' },
    { label: '最近更新时间', value: 'updateTime' },
    { label: '存储条件', value: 'storageCondition' },
    { label: '备注', value: 'remark', type: 'popover' },
    {
      label: '附件',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
  ],
})
// 操作流水
const affairTableInfo = ref({
  api: orderOpAffairAll,
  query: {
    orderType: 94,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})
const licenseInfoList = ref({
  data: {
    isConsignment: 0,
    withOperateTable: 0,
  },
  fieldList: [
    { label: '证号', value: 'licenseNumber', type: 'slot' },
    { label: '证照名称', value: 'licenseName', type: 'text' },
    { label: '英文名称', value: 'enName', type: 'text' },
    { label: '证照生效日期', value: 'licenseBeginDate', type: 'text' },
    { label: '证照失效日期', value: 'licenseEndDate', type: 'text' },
    { label: '包装规格', value: 'packedStandard', type: 'text' },

    { label: '生产厂家', value: 'brandName', type: 'slot' },
  ],
})
const controlInfoList = ref({
  data: {
    isConsignment: 0,
    withOperateTable: 0,
  },
  fieldList: [
    {
      label: '近效期（天）',
      value: 'productNearlyEffective',
      type: 'text',
    },

    {
      label: '需要批号效期',
      value: 'needBatchNumberValue',
      type: 'text',
    },
    {
      label: '需要序列管理',
      value: 'needSequenceValue',
      type: 'text',
    },
    { label: '以领定消', value: 'acquisitionReplaceConsumeValue' },

    { label: '是否议价', value: 'isBargainingValue' },

    { label: '是否收费', value: 'isChargeValue' },
    { label: '是否寄售', value: 'isConsignmentValue' },
    { label: '手术跟台', value: 'withOperateTableValue', type: 'text' },
    { label: '结算方式', value: 'settlementMethodValue' },
    { label: '限制价格', value: 'isLimitPriceValue' },
    { label: '采购限制价格', value: 'purchaseLimitPrice' },
    {
      label: '是否RFID管理',
      value: 'isRfidManageValue',
    },
    { label: '厂家理论测试次数', value: 'expectedUsageTimes' },
    { label: '院内理论测试次数', value: 'hospitalExpectedUsageTimes' },
    { label: '计费次数', value: 'chargeTimes' },
    { label: '重点监控高值医用耗材', value: 'importantHighMaterialValue' },
    { label: '是否集采', value: 'isCollectivePurchaseValue' },
    { label: '集采项目号', value: 'collectivePurchaseBatchValue' },
    { label: '付款类型', value: 'paymentTypeValue' },
  ],
})
const spreadInfoList = ref({
  data: {
    isConsignment: 0,
    withOperateTable: 0,
  },
  fieldList: [
    { label: '是否挂网', value: 'isSunPurchaseValue' },
    { label: '挂网类型', value: 'networkTypeValue', type: 'text' },
    { label: '挂网产品类型', value: 'networkProductTypeValue', type: 'text' },
    { label: '商品代码', value: 'serialNum', type: 'text' },
    {
      label: '挂网耗材产品id',
      value: 'procureCatalogId',
      type: 'text',
      show: false,
    },
    { label: '挂网单位', value: 'networkUnit', type: 'text' },
    { label: '单位比例', value: 'networkUnitCoefficient', type: 'slot' },
    { label: '挂网单价', value: 'networkPrice', type: 'text' },
  ],
})
const classifyInfoList = ref({
  //分类信息
  data: {
    isConsignment: 0,
    withOperateTable: 0,
  },
  fieldList: [
    { label: '财务科目', value: 'financialAccountValue', type: 'text' },

    { label: '防疫物资', value: 'epidemicPreventionValue' },
    { label: '临采产品', value: 'temporaryPurchValue' },
    { label: '发票类别', value: 'invoiceCategoryValue' },
    { label: '病案类别', value: 'caseCategoryValue' },
    { label: '质管类型', value: 'dosageFormValue', type: 'text' },
    {
      label: '库存类别',
      value: 'inventoryCategoriesValue',
      type: 'text',
    },
    { label: '产品分类', value: 'productCategoryValue', type: 'text' },

    {
      label: '项目分类',
      value: 'projectClassificationValue',
      type: 'text',
    },
    {
      label: '品种',
      value: 'varietiesName',
      type: 'text',
    },
    {
      label: '住院收据费用分类',
      value: 'classificationOfHospitalReceiptsValue',
      type: 'text',
    },
    {
      label: '门诊收据费用分类',
      value: 'outpatientReceiptFeeClassificationValue',
      type: 'text',
    },
    {
      label: '核算项目分类',
      value: 'accountingItemClassificationValue',
      type: 'text',
    },
    {
      label: '病案首页费用分类',
      value: 'medicalRecordsFirstPageCostClassificationValue',
      type: 'text',
    },
    { label: '项目等级', value: 'projectLevelValue', type: 'text' },
    {
      label: '收费项目会计子分类',
      value: 'chargeItemCategoryValue',
      type: 'text',
    },
    { label: '医嘱子类', value: 'adviceCategoryValue', type: 'text' },
    {
      label: '独立医嘱标记',
      value: 'independentAdviceMarkValue',
      type: 'text',
    },
    { label: '医嘱优先级', value: 'advicePriorityValue', type: 'text' },
    { label: '新病案首页费用分类', value: 'newMedicalRecordsFirstPageCostClassificationValue', type: 'text' },
  ],
})

const medicareInfoList = ref({
  //医保信息
  data: {
    isConsignment: 0,
    withOperateTable: 0,
  },
  fieldList: [
    { label: '国家医保编码', value: 'nationCode', type: 'text' },
    { label: '省医保编码', value: 'provinceCode', type: 'text' },
    {
      label: '国家医保名称',
      value: 'nationHealthInsurance',
      type: 'text',
    },
  ],
})
const bidderInfoList = ref({
  //医保信息
  data: {},
  fieldList: [
    { label: '试剂归属', value: 'reagentScopeValue', type: 'text' },
    { label: '是否中标', value: 'isWinningValue', type: 'text' },
    {
      label: '中标批次',
      value: 'winningBatchValue',
      type: 'text',
    },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    productId: props.id,
    sort: 'is_default desc,create_time desc',
  },
  list: [],
})
const adjustPriceFilterInfo = ref({
  query: {
    productId: props.id,
  },
})
const licenseDetail = ref({
  visible: false,
  id: '',
})
// 表格相关
const tableInfo = ref({
  data: [],
  fieldList: [
    { label: '供应商', value: 'supplierName', type: 'slot' },
    { label: '机构代码', value: 'supplierCode' },
    { label: '合同编码', value: 'orderNo', type: 'slot' },

    { label: '联系人', value: 'contact' },
    { label: '联系电话', value: 'contactNumber' },
    { label: '是否默认', value: 'isDefaultValue' },
    { label: '价格', value: 'price', formatter: proxy.$fn.TripartiteMethod },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '设为默认',
        event: setDefault,
        show: true,
        ifRender: function (row) {
          return row.isDefault !== 1
        },
      },
    ],
  },
})
//调价记录表格
const adjustPriceTableInfo = ref({
  data: [],
  fieldList: [
    { label: '供应商', value: 'supplierName' },
    { label: '调价前价格', value: 'beforePrice' },
    { label: '调价后价格', value: 'afterPrice' },
    { label: '调价原因', value: 'adjustReason' },
    { label: '生效日期', value: 'effectiveDate' },
  ],
  handle: {},
})
const showModify = ref({
  title: '修改产品',
  type: 'update',
  isCopy: false,
  visible: false,
})
const btnList = ref([
  { label: '修改', event: update, show: proxy.$permission('product:update') },
  {
    label: '复制并新增',
    event: copyToadd,
    show: proxy.$permission('product:copyToadd'),
  },
])
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    // 更新父组件visible
    emits('update:visible', val)
  },
})
watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  {
    immediate: true,
  }
)
watch(
  () => infoList.value.data.isConsignment,
  (value) => {
    if (value == 1) {
      showControlFieldListItem(true, 'withOperateTableValue')
    } else {
      showControlFieldListItem(false, 'withOperateTableValue')
    }
  }
)

function showLicenseDetail() {
  licenseDetail.value.visible = true
  licenseDetail.value.id = infoList.value.data.licenseId
}
function showControlFieldListItem(show, nameValue) {
  let fieldList = controlInfoList.value.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function handleClick(tab) {
  const name = tab.paneName
  activeName.value = tab.paneName
  if (name == 'supplier') {
    getList()
  } else if (name == 'modifyPrice') {
    getAdjustPriceList()
  }
}
function returnBack() {
  emits('returnBack', false)
}
// 获取列表
function getList() {
  getSupplierProductAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
    }
  })
}
function getAdjustPriceList() {
  adjustPriceSelectByProductId(adjustPriceFilterInfo.value.query).then(
    (res) => {
      if (res && res.success) {
        adjustPriceTableInfo.value.data = res.data
      }
    }
  )
}
//设置默认
function setDefault(row) {
  setSupplierProductDefault(row.id).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function getDetails() {
  getProductById(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
      if (
        infoList.value.data.codeType == 3 ||
        infoList.value.data.codeType == 2
      ) {
        if (
          infoList.value.data.g1 &&
          infoList.value.data.g1.type === 'GS1_OTHER'
        ) {
          const eg = []
          infoList.value.data.g1.coreProductRuleVOList.map((item) => {
            eg.push(
              String(
                '(' +
                  item.ruleCode +
                  ')' +
                  stringFillCharacter(Number(item.ruleLength))
              )
            )
            delete item.disabledCode
            delete item.key
            return item
          })
          infoList.value.data.g1Type = eg.toString().replace(/,/g, '')
        } else {
          infoList.value.data.g1Type = 'GS1规则'
        }
      } else {
        infoList.value.data.g1Type = ''
      }
      if (
        infoList.value.data?.chargeTimes &&
        infoList.value.data?.chargeTimes === -2
      ) {
        infoList.value.data.chargeTimes = ''
      }
      licenseInfoList.value.data = infoList.value.data
      controlInfoList.value.data = infoList.value.data
      spreadInfoList.value.data = infoList.value.data
      classifyInfoList.value.data = infoList.value.data
      medicareInfoList.value.data = infoList.value.data
      bidderInfoList.value.data = infoList.value.data
      if (infoList.value.data.procureCatalogId) {
        spreadInfoList.value.fieldList.forEach((item) => {
          if (item.value === 'procureCatalogId') {
            item.show = true
          }
        })
      }
    }
  })
}
function stringFillCharacter(length) {
  return new Array(length + 1).join('x')
}
function modifyCallback() {
  getDetails()
  getList()
  getAdjustPriceList()
}
function update() {
  showModify.value.visible = true
  showModify.value.type = 'update'
  showModify.value.title = '修改产品'
  showModify.value.isCopy = false
}
function copyToadd() {
  showModify.value.visible = true
  showModify.value.type = 'create'
  showModify.value.isCopy = true
  showModify.value.title = '复制并新增'
}
function showSupplier(row) {
  proxy.$router.push({
    name: 'supplier',
    params: {
      supplierId: row.supplierId,
    },
  })
}
function showOrder(row) {
  let name = ''
  let routes = proxy.$store.state.permission.routes
  routes.map((item) => {
    if (item.children && item.children.length) {
      item.children.map((i) => {
        if (i.url === '/contractManage/contract') {
          name = '/contractManage/contract'
        }
      })
    }
  })
  if (name) {
    proxy.$router.push({
      name: 'contract',
    })
    let params = {
      businessId: row.id,
      url: name,
      urlType: 2,
    }
    proxy.$store.dispatch('settings/toPage', params)
  }
}
function showBrandDetail() {
  emits('toggleBrandDetail', infoList.value.data.brandId)
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'productDetailPrint',
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            productId: infoList.value.data.id,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      productId: props.id,
      tempCode: 'productDetailPrint',
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      productId: infoList.value.data.id,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
onMounted(() => {
  getDetails()
  getList()
})
</script>
